package jp.sinya.temicontact;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewStub;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.Toast;

import jp.sinya.temicontact.adapter.ContactListAdapter;
import jp.sinya.temicontact.mvp.model.Contact;
import jp.sinya.temicontact.mvp.presenter.ContactListPresenter;
import jp.sinya.temicontact.mvp.view.ContactListView;
import jp.sinya.temicontact.utils.DialogUtils;
import jp.sinya.temicontact.utils.LogUtils;

/**
 * @author Koizumi Sinya
 * @date 2018/01/11. 20:55
 * @edithor
 * @date
 */
public class MainActivity extends AppCompatActivity implements ContactListView, SplashFragment.SplashCallback {

    private SwipeRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private ContactListPresenter presenter;
    private ContactListAdapter adapter;
    private LinearLayoutManager layoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //先加载网络数据，利用splash页面启动的时间 同时把数据加载回来
        presenter = new ContactListPresenter(this);
        presenter.request(false);

        //splash启动页面
        initFragment();
    }

    private void init(View view) {
        refreshLayout = view.findViewById(R.id.refresh_layout);
        recyclerView = view.findViewById(R.id.recycler_view);

        initRecyclerView();
        initRefreshLayout();
    }

    private void initRecyclerView() {
        adapter = new ContactListAdapter(this, null);
        layoutManager = new LinearLayoutManager(this);

        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new ContactListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                clickListItem(adapter.getItem(position));
            }
        });
    }

    private void initRefreshLayout() {
        refreshLayout.setColorSchemeColors(//
                getResources().getColor(R.color.colorPrimary),//
                getResources().getColor(R.color.colorAccent), //
                getResources().getColor(R.color.colorPrimaryDark));

        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        LogUtils.Sinya("下拉刷新...");
                        presenter.request(true);
                    }
                }, 100);
            }
        });
    }

    private void clickListItem(Contact contact) {
        Intent intent = new Intent(this, ContactDetailActivity.class);
        intent.putExtra("contact", contact);
        startActivity(intent);
        // 淡出淡入动画效果
        overridePendingTransition(R.anim.activity_out_anim, R.anim.activity_in_anim);
    }

    private void initFragment() {
        SplashFragment splashFragment = new SplashFragment();
        splashFragment.setSplashCallback(this);
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        transaction.replace(R.id.fl_splash, splashFragment, "splash");
        transaction.commit();
    }

    private void removeFragment() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        Fragment fragment = fragmentManager.findFragmentById(R.id.fl_splash);
        transaction.remove(fragment);
    }

    @Override
    public void finishCallback() {
        removeFragment();

        ViewStub viewStub = findViewById(R.id.main_activity_content);
        View view = viewStub.inflate();
        init(view);

        if (!presenter.isLoading() && presenter.getContactList() != null) {
            loadData();
            LogUtils.Sinya("splash加载完后，网络请求的数据已取回，直接显示");

        } else if (!presenter.isLoading() && presenter.getContactList() == null) {
            presenter.request(false);
            LogUtils.Sinya("splash加载完后，网络请求的数据为空，再尝试请求一次");

        } else if (presenter.isLoading()) {
            presenter.setAutoLoad(true);
            LogUtils.Sinya("splash加载完后，网络请求还在执行中");
            DialogUtils.get().showLoadDialog(this, "loading...", false);
        }
    }

    @Override
    public void showLoading() {
        if (refreshLayout != null) {
            refreshLayout.setRefreshing(true);
        }
    }

    @Override
    public void closeLoading() {
        if (refreshLayout != null) {
            refreshLayout.setRefreshing(false);
        }
        DialogUtils.get().closeLoadDialog();
    }

    @Override
    public void showError(String err) {
        Toast.makeText(this, err, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void loadData() {
        adapter.setDataList(presenter.getContactList());
        refreshRecyclerView();
    }

    private void refreshRecyclerView() {
        LayoutAnimationController controller = AnimationUtils.loadLayoutAnimation(this, R.anim.layout_anim);
        recyclerView.setLayoutAnimation(controller);
        recyclerView.scheduleLayoutAnimation();
    }

}
